package cn.akwangl.service.impl;

import cn.akwangl.common.Constant;
import cn.akwangl.exception.BizException;
import cn.akwangl.pojo.User;
import cn.akwangl.service.LoginService;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.LocalDate;

/**
 * 本地登录实现.
 *
 * @author youyongkun
 * @date 2022/5/17 11:41
 */
@Service(LocalLoginServiceImpl.BEAN_NAME)
public class LocalLoginServiceImpl implements LoginService {

    public static final String BEAN_NAME = "LocalLoginService";

    private User localUser;

    @PostConstruct
    public void init() {
        localUser = new User(100L, "admin", "123456", "3rfa2q", LocalDate.of(2021, 02, 9));
    }

    @Override
    public String login(String username, String pwd) {
        String cacheUserName = localUser.getName();
        String cachePwd = localUser.getPwd();

        boolean hasSuccess = cacheUserName.equals(username) && cachePwd.equals(pwd);
        if (hasSuccess) {
            DateTime expireDate = DateUtil.date().offset(DateField.DAY_OF_YEAR, 7);
            long expire = expireDate.getTime();

            String token = JWT.create()
                    .setPayload("id", localUser.getId())
                    .setPayload("name", localUser.getName())
                    .setPayload("admin", true)
                    .setPayload("expire", expire)
                    .setKey(Constant.jwtKey.getBytes())
                    .sign();
            return token;
        } else {
            throw new BizException("账号或密码错误，请重试");
        }
    }
}
